﻿using System;
using System.ComponentModel.Composition;
using Cubicle.Core.Interfaces;

namespace Cubicle.Core.Processors.Invoke
{
    [Export("Cubicle.Processors.Invoke.TypeResolutionProcessor", typeof(IProcessor<InstructionRequest>))]
    [ExportMetadata("Name", "TypeResolutionProcessor")]
    [ExportMetadata("Description", "Resolves the type of the target whether the target is an instance in the repository or a static member.")]
    public class TypeResolutionProcessor : InstructionRequestProcessor
    {
        #region Overrides of Processor

        public TypeResolutionProcessor() : base(RequestType.AllNonSpecial) { }

        public override InstructionRequest ConditionalProcess(InstructionRequest request)
        {
            // Virtual
            if (request.Target != null)
            {
                request.TargetType = request.Target.GetType();
                return request;
            }
            
            // Static
            request.TargetType = Type.GetType(request.Inst.Handle, true, true);
            if (request.TargetType != null)
                return request;

            // Fail
            request.Fail("Target not found. InstructionId = {0}", request.Id);
            return request;
        }

        #endregion
    }
}